from sys import flags
import scapy
import csv
from scapy.all import *
from scapy.utils import PcapReader
# from nfstream import NFStreamer
import pandas as pd

pd.set_option('display.width', None)

packets = rdpcap("E:/跑代码测试文件夹/ss5_3-4-4.pcap")


# with open('C:/Users/yinwe/Desktop/test.csv', mode='a',encoding='utf-8-sig', newline='') as csvfile:
#     writer = csv.writer(csvfile)
#     for i in range(0,10):
#         writer.writerow(['xxx','xxx',i])

i = 0
j = 0
while(True):
    if packets[j].haslayer("TCP"):
        upsrc = packets[j].payload.src
        downsrc = packets[j].payload.dst
        print(upsrc,'   ',downsrc)
        break
    j = j+1

for data in packets:
    if data.haslayer("TCP"):
        if data.payload.src == downsrc and data.payload.dst== upsrc and len(data["TCP"].payload.original)!=0:
        # print(data.payload.payload.flags)
#         if 'TCP' in data:
#         #if Raw in data:
        # print(data.time)
            with open('E:/跑代码测试文件夹/test1.csv', mode='a',encoding='utf-8-sig', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([i, 'down', data.payload.src, data.payload.sport, data.payload.dst, data.payload.dport, data.payload.payload.flags, len(data["TCP"].payload.original)])
                # print("%5d|"%i,'down|',data.payload.src.ljust(15),':',"%5s"%data.payload.sport,'-->',data.payload.dst.ljust(15),':',"%5s"%data.payload.dport, "%4s"%data.payload.payload.flags ,len(data["TCP"].payload.original))
        elif data.payload.src== upsrc and data.payload.dst== downsrc and len(data["TCP"].payload.original)!=0:
            with open('E:/跑代码测试文件夹/test1.csv', mode='a',encoding='utf-8-sig', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([i, 'up', data.payload.src, data.payload.sport, data.payload.dst, data.payload.dport, data.payload.payload.flags, len(data["TCP"].payload.original)])
                # print("%5d|"%i,' up |',data.payload.src.ljust(15),':',"%5s"%data.payload.sport,'-->',data.payload.dst.ljust(15),':',"%5s"%data.payload.dport, "%4s"%data.payload.payload.flags ,len(data["TCP"].payload.original))
    i = i + 1
